import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_template/core/http/http.dart';
import 'package:flutter_template/core/utils/toast.dart';
import 'package:flutter_template/core/utils/verify.dart';
import 'package:flutter_template/core/widget/loading_dialog.dart';
import 'package:flutter_template/generated/i18n.dart';
import 'dart:async';

class ForgetPassPage extends StatefulWidget {
  @override
  _ForgetPassPageState createState() => _ForgetPassPageState();
}

class _ForgetPassPageState extends State<ForgetPassPage> {
  bool _isShowPassWord = false;
  bool _isShowPassWordRepeat = false;
  // 响应空白处的焦点的Node
  FocusNode blankNode = FocusNode();
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  TextEditingController _codeController = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();

  // 区号列表
  List<areaCodeObj> areaList;
  // 默认大陆手机区号+86
  String areaCode = '86';
  // 验证码倒计时
  Timer _timer;
  int _countdownTime = 0;
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    areaList = new List();
    areaList
      ..add(areaCodeObj('中国大陆', '86'))
      ..add(areaCodeObj('中国香港', '852'))
      ..add(areaCodeObj('中国澳门', '853'));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(I18n.of(context).forgetPassword)),
      body: GestureDetector(
        onTap: () {
          // 点击空白页面关闭键盘
          closeKeyboard(context);
        },
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
          child: buildForm(context),
        ),
      ),
    );
  }

  //构建表单
  Widget buildForm(BuildContext context) {
    return Form(
      key: _formKey, //设置globalKey，用于后面获取FormState
      autovalidate: false,
      child: Column(
        children: <Widget>[
          // 手机号
          Container(
              margin: EdgeInsets.only(top: 20),
              decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(
                        width: 1, color: ColorUtil.color("#17181C00"))),
              ),
              child:
                  // 手机号
                  Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  // 区号选择器
                  _areaCodeSelector(context, areaList),
                  Expanded(
                    flex: 1,
                    child: TextFormField(
                        autofocus: false,
                        controller: _phoneController,
                        decoration: InputDecoration(
                            hintText: I18n.of(context).loginNameHint,
                            hintStyle: TextStyle(fontSize: 18),
                            border: InputBorder.none),
                        //校验用户名
                        validator: (v) {
                          return v.trim().length > 0
                              ? null
                              : I18n.of(context).loginNameError;
                        }),
                  ),
                ],
              )),
          // 验证码
          Container(
              margin: EdgeInsets.only(top: 20),
              decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(
                        width: 1, color: ColorUtil.color("#17181C00"))),
              ),
              child:
                  Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
                Expanded(
                  flex: 1,
                  child: TextFormField(
                      controller: _pwdController,
                      decoration: InputDecoration(
                          hintText: I18n.of(context).codeHint,
                          hintStyle: TextStyle(fontSize: 18),
                          border: InputBorder.none),
                      //校验密码
                      validator: (v) {
                        return v.trim().length >= 6
                            ? null
                            : I18n.of(context).codeError;
                      }),
                ),
                // 发送验证码
                FlatButton(
                  child: Text(_countdownTime > 0
                      ? '${_countdownTime}s ${I18n.of(context).countTimeText}'
                      : '${I18n.of(context).getCodeText}'),
                  color: Theme.of(context).primaryColor,
                  textColor: Colors.white,
                  onPressed: () {
                    if (_countdownTime == 0 &&
                        isMobilePhoneNumber(_phoneController.text)) {
                      //Http请求发送验证码

                      setState(() {
                        _countdownTime = 60;
                      });
                      //开始倒计时
                      startCountdownTimer();
                    } else if (!isMobilePhoneNumber(_phoneController.text)) {
                      ToastUtils.waring('${I18n.of(context).phoneError}');
                    } else {
                      ToastUtils.waring('${I18n.of(context).repeatClick}');
                    }
                  },
                )
              ])),
          // 重置密码
          Container(
            margin: EdgeInsets.only(top: 20),
            decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      width: 1, color: ColorUtil.color("#17181C00"))),
            ),
            child: TextFormField(
                controller: _codeController,
                decoration: InputDecoration(
                    hintText: I18n.of(context).newPasswordHint,
                    hintStyle: TextStyle(fontSize: 18),
                    border: InputBorder.none,
                    suffixIcon: IconButton(
                        icon: Icon(
                          _isShowPassWordRepeat
                              ? Icons.visibility
                              : Icons.visibility_off,
                          color: Colors.black,
                        ),
                        onPressed: showPassWordRepeat)),
                obscureText: !_isShowPassWordRepeat,
                //校验密码
                validator: (v) {
                  return v.trim().length >= 6
                      ? null
                      : I18n.of(context).passwordError;
                }),
          ),

          // 登录按钮
          Padding(
            padding: const EdgeInsets.only(top: 28.0),
            child: Row(
              children: <Widget>[
                Expanded(child: Builder(builder: (context) {
                  return RaisedButton(
                    padding: EdgeInsets.all(15.0),
                    child: Text(I18n.of(context).resetPassword),
                    color: Theme.of(context).primaryColor,
                    textColor: Colors.white,
                    onPressed: () {
                      //由于本widget也是Form的子代widget，所以可以通过下面方式获取FormState
                      if (Form.of(context).validate()) {
                        onSubmit(context);
                      }
                    },
                  );
                })),
              ],
            ),
          )
        ],
      ),
    );
  }

  ///点击控制密码是否显示
  void showPassWord() {
    setState(() {
      _isShowPassWord = !_isShowPassWord;
    });
  }

  ///点击控制密码是否显示
  void showPassWordRepeat() {
    setState(() {
      _isShowPassWordRepeat = !_isShowPassWordRepeat;
    });
  }

  void closeKeyboard(BuildContext context) {
    FocusScope.of(context).requestFocus(blankNode);
  }

  //验证通过提交数据
  void onSubmit(BuildContext context) {
    closeKeyboard(context);

    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return LoadingDialog(
            showContent: false,
            backgroundColor: Colors.black38,
            loadingView: SpinKitCircle(color: Colors.white),
          );
        });

    XHttp.post("/user/register", {
      "phone": _phoneController.text,
      "password": _pwdController.text,
      "code": _codeController.text
    }).then((response) {
      Navigator.pop(context);
      if (response['errorCode'] == 0) {
        ToastUtils.toast(I18n.of(context).registerSuccess);
        Navigator.of(context).pop();
      } else {
        ToastUtils.error(response['errorMsg']);
      }
    }).catchError((onError) {
      Navigator.of(context).pop();
      ToastUtils.error(onError);
    });
  }

  Widget _areaCodeSelector(BuildContext context, List<areaCodeObj> list) {
    List<PopupMenuItem> menuList;
    menuList = list.map((element) {
      return PopupMenuItem(
        value: element.code,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              child: Text('${element.area}'),
            ),
            Container(
              child: Text('${element.code}'),
            )
          ],
        ),
      );
    }).toList();

    return Container(
      child: Row(
        children: [
          Text(
            "+$areaCode",
            style: TextStyle(fontSize: 18),
          ),
          PopupMenuButton(
            icon: Icon(Icons.arrow_drop_down),
            initialValue: areaCode,
            itemBuilder: (context) {
              return menuList;
            },
            onSelected: (value) {
              setState(() {
                areaCode = value;
              });
            },
          )
        ],
      ),
    );
  }

// 倒计时的实现方法
  void startCountdownTimer() {
    const oneSec = const Duration(seconds: 1);

    var callback = (timer) => {
          setState(() {
            if (_countdownTime < 1) {
              _timer.cancel();
            } else {
              _countdownTime = _countdownTime - 1;
            }
          })
        };

    _timer = Timer.periodic(oneSec, callback);
  }
}

class areaCodeObj {
  String code;
  String area;
  areaCodeObj(this.area, this.code);
}
